﻿/*
 * QWine Queue Machine (Special build for Immigration Office)
 * Copyright (C) 2010 Wish Enterprise Development Team

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact Us:
 * E-Mail   : contact@wishenterprise.com
 * 
 * */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using QWEntity.Local;
using QWModel;
using QWRepository;
using QWRepository.Local;
using QWScreenPanel.Model;
using QWScreenPanel.Properties;

namespace QWScreenPanel
{
    /// <summary>
    /// MainScreen : Form
    /// </summary>
    public partial class MainScreen : Form
    {
        /// <summary>
        /// TemporaryNumber: Bayar
        /// </summary>
        private readonly TemporaryNumber _tmpBayar = new TemporaryNumber();

        /// <summary>
        /// TemporaryNumber: Berkas
        /// </summary>
        private readonly TemporaryNumber _tmpBerkas = new TemporaryNumber();

        /// <summary>
        /// TemporaryNumber: Foto
        /// </summary>
        private readonly TemporaryNumber _tmpFoto = new TemporaryNumber();

        /// <summary>
        /// TemporaryNumber: Wawancara
        /// </summary>
        private readonly TemporaryNumber _tmpWawancara = new TemporaryNumber();

        /// <summary>
        /// Clock
        /// </summary>
        private QWClock _clockWidget;

        /// <summary>
        /// Berkas Repo
        /// </summary>
        private BerkasBase _dbBerkas;

        /// <summary>
        /// Kasir Repo
        /// </summary>
        private KasirBase _dbKasir;

        /// <summary>
        /// KeyMap
        /// </summary>
        private Keymap _keymap;

        /// <summary>
        /// Lokets
        /// </summary>
        private List<Loket> _lokets;

        /// <summary>
        /// Press Images
        /// </summary>
        private QWPress _pressWidget;

        /// <summary>
        /// Processing status
        /// </summary>
        private bool _stillProcessing;

        /// <summary> 
        /// Initializes a new instance of the <see cref="MainScreen"/> class.
        /// </summary>
        public MainScreen()
        {
            /* --------------------------------------
             *  load connections
             * -------------------------------------- */
            //var tbase = new Thread(TBase);
            //tbase.Start();

            /* --------------------------------------
             *  default value
             * -------------------------------------- */
            _stillProcessing = false;
            _tmpBayar.ID = "B";
            _tmpBayar.ReplayID = "B";
            _tmpFoto.ID = "B";
            _tmpFoto.ReplayID = "B";
            _tmpWawancara.ID = "B";
            _tmpWawancara.ReplayID = "B";

            /* --------------------------------------
             *  load background image
             * -------------------------------------- */
            //var tb = new Thread(TBackgroundImage);
            //tb.Start();

            InitializeComponent();

            Parallel.Invoke(
                TBase,
                SetBackgroundImage,
                SetPanel1Image,
                SetPanel2Image,
                SetPanel3Image,
                SetPanel4Image,
                SetPanelPressImage,
                TLoket,
                LoadPressImages);


            /* --------------------------------------
             *  load panel 1 background image
             * -------------------------------------- */
            //var t1 = new Thread(TPanel1Image);
            //t1.Start();

            /* --------------------------------------
             *  load pabel 2 background image
             * -------------------------------------- */
            //var t2 = new Thread(TPanel2Image);
            //t2.Start();

            /* --------------------------------------
             *  load panel 3 background image
             * -------------------------------------- */
            //var t3 = new Thread(TPanel3Image);
            //t3.Start();

            /* --------------------------------------
             *  load panel 4 background image
             * -------------------------------------- */
            //var t4 = new Thread(TPanel4Image);
            //t4.Start();

            /* --------------------------------------
             *  load panel press background image
             * -------------------------------------- */
            //var tpress = new Thread(SetPanelPressImage);
            //tpress.Start();

            /* --------------------------------------
             *  load loket information
             * -------------------------------------- */
            //var tloket = new Thread(TLoket);
            //tloket.Start();

            /* -------------------------------
            *  load PRES
            * ------------------------------- */
            //var tp = new Thread(LoadPressImages);
            //tp.Start();
        }


        /// <summary>
        /// Ts the base.
        /// </summary>
        private void TBase()
        {
            _dbBerkas = new BerkasBase();
            _dbKasir = new KasirBase();
        }

        /// <summary>
        /// Ts the loket.
        /// </summary>
        private void TLoket()
        {
            if (InvokeRequired)
            {
                var o = new DelegateThis(TLoket);
                Invoke(o);
            }
            else
            {
                /* --------------------------------------
                 *  all lokets
                 * -------------------------------------- */
                _lokets = new LoketBase().GetAll();

                /* --------------------------------------
                 *  show each panel header
                 * -------------------------------------- */
                foreach (Loket r in _lokets)
                {
                    switch (r.LoketID)
                    {
                        case "BERKAS":
                            lblHeader1.Text = string.Format("Loket: {0}", r.LoketDescription);
                            break;
                        case "BAYAR":
                            lblHeader2.Text = string.Format("Loket: {0}", r.LoketDescription);
                            break;
                        case "FOTO":
                            lblHeader3.Text = string.Format("Loket: {0}", r.LoketDescription);
                            break;
                        case "WAWANCARA":
                            lblHeader4.Text = string.Format("Loket: {0}", r.LoketDescription);
                            break;
                    }
                }
            }
        }


        /// <summary>
        /// Handles the KeyDown event of the MainScreen control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
        private void MainScreen_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                _clockWidget.Dispose();
                _pressWidget.Dispose();

                ApplicationExit();
            }
        }

        /// <summary>
        /// Applications the exit.
        /// </summary>
        private void ApplicationExit()
        {
            Close();
            Dispose();
            Application.Exit();
        }

        /// <summary>
        /// Ts the play bell.
        /// </summary>
        private static void TPlayBell()
        {
            WavPlayer.PlaySound("null");
        }

        /// <summary>
        /// Handles the KeyUp event of the MainScreen control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
        private void MainScreen_KeyUp(object sender, KeyEventArgs e)
        {
            if (_stillProcessing) return;

            /* --------------------------------------
             *  keymaps
             * -------------------------------------- */
            var db = new KeymapBase();
            _keymap = db.GetById(e.KeyCode.ToString().Trim());
            db.Dispose();

            /* --------------------------------------
             *  null keymaps
             * -------------------------------------- */
            if (_keymap == null)
                return;

            // status
            _stillProcessing = true;
            Application.DoEvents();

            /* --------------------------------------
             *  get loket information
             * -------------------------------------- */
            string loketid = _keymap.LoketID.ToUpper().Trim();
            string loketDesc = "";
            foreach (Loket r in _lokets.Where(r => r.LoketID == loketid))
                loketDesc = r.LoketDescription;

            /* --------------------------------------
             *  loket switching
             * -------------------------------------- */
            switch (loketid)
            {
                case "BERKAS":

                    /* -------------------------------
                     *  if NEXT
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                        _tmpBerkas.Nomor = _dbBerkas.GetNextNumber();

                    /* -------------------------------
                     *  if NOT FOUND
                     * ------------------------------- */
                    if (_tmpBerkas.Nomor == 0)
                    {
                        var tbell = new Thread(TPlayBell);
                        tbell.Start();
                        Thread.Sleep(100);

                        break;
                    }

                    /* -------------------------------
                     *  set value for calling
                     * ------------------------------- */
                    _tmpBerkas.ID = "A";
                    _tmpBerkas.NomorAntrian =
                        string.Format("{0}-{1}", _tmpBerkas.ID,
                                      _tmpBerkas.Nomor.ToString().Trim().PadLeft(3, '0'));

                    _tmpBerkas.LoketID = loketid;
                    _tmpBerkas.LoketDescription = loketDesc;

                    /* -------------------------------
                     *  calling
                     * ------------------------------- */
                    //var trBerkas = new Thread(TCallBerkas);
                    //trBerkas.Start();
                    //Thread.Sleep(100);
                    TCallBerkas();

                    /* -------------------------------
                     *  if NEXT, update called 
                     *  status
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                        _dbBerkas.UpdateCalled(_tmpBerkas.Nomor);

                    /* -------------------------------
                     *  show on BOX
                     * ------------------------------- */
                    lblBerkas.Text = _tmpBerkas.NomorAntrian;
                    lblBerkas.Refresh();

                    break;

                case "BAYAR":

                    /* -------------------------------
                     *  if NEXT
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        int i = 0;
                        int n = 0;

                        /* -------------------------------
                         *  FLIP FLOP
                         * ------------------------------- */
                        while (i == 0 && n <= 1)
                        {
                            /* get next number
                             * by current id */
                            _tmpBayar.Nomor = _dbKasir.GetKasirNextNumber(_tmpBayar.ID);
                            i = _tmpBayar.Nomor;
                            n++;

                            /* if not found, convert id into another
                             * and repeat the process */
                            if (i == 0) _tmpBayar.ID = ConvertID(_tmpBayar.ID);
                            _tmpBayar.ReplayID = _tmpBayar.ID;
                        }
                    }

                    /* -------------------------------
                     *  if NOT FOUND
                     * ------------------------------- */
                    if (_tmpBayar.Nomor == 0)
                    {
                        var tbell = new Thread(TPlayBell);
                        tbell.Start();
                        Thread.Sleep(100);

                        break;
                    }

                    /* -------------------------------
                     *  set value for calling
                     * ------------------------------- */
                    _tmpBayar.NomorAntrian =
                        string.Format("{0}-{1}", _tmpBayar.ReplayID,
                                      _tmpBayar.Nomor.ToString().Trim().PadLeft(3, '0'));

                    _tmpBayar.LoketID = loketid;
                    _tmpBayar.LoketDescription = loketDesc;

                    /* -------------------------------
                     *  calling
                     * ------------------------------- */
                    //var trBayar = new Thread(TCallBayar);
                    //trBayar.Start();
                    //Thread.Sleep(100);
                    TCallBayar();

                    /* -------------------------------
                     *  if NEXT, update called 
                     *  status
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        _dbKasir.UpdateKasirCalled(_tmpBayar.ID, _tmpBayar.Nomor);
                        _tmpBayar.ID = ConvertID(_tmpBayar.ID);
                    }

                    /* -------------------------------
                     *  show on BOX
                     * ------------------------------- */
                    lblKasir.Text = _tmpBayar.NomorAntrian;
                    lblKasir.Refresh();

                    break;

                case "FOTO":

                    /* -------------------------------
                     *  if NEXT
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        int i = 0;
                        int n = 0;

                        /* -------------------------------
                         *  FLIP FLOP
                         * ------------------------------- */
                        while (i == 0 && n <= 1)
                        {
                            /* get next number
                             * by current id */
                            _tmpFoto.Nomor = new KasirBase().GetFotoNextNumber(_tmpFoto.ID);
                            i = _tmpFoto.Nomor;
                            n++;

                            /* if not found, convert id into another
                             * and repeat the process */
                            if (i == 0) _tmpFoto.ID = ConvertID(_tmpFoto.ID);
                            _tmpFoto.ReplayID = _tmpFoto.ID;
                        }
                    }

                    /* -------------------------------
                     *  if NOT FOUND
                     * ------------------------------- */
                    if (_tmpFoto.Nomor == 0)
                    {
                        var tbell = new Thread(TPlayBell);
                        tbell.Start();
                        Thread.Sleep(100);

                        break;
                    }

                    /* -------------------------------
                     *  set value for calling
                     * ------------------------------- */
                    _tmpFoto.NomorAntrian =
                        string.Format("{0}-{1}", _tmpFoto.ReplayID,
                                      _tmpFoto.Nomor.ToString().Trim().PadLeft(3, '0'));

                    _tmpFoto.LoketID = loketid;
                    _tmpFoto.LoketDescription = loketDesc;

                    /* -------------------------------
                     *  calling
                     * ------------------------------- */
                    //var trFoto = new Thread(TCallFoto);
                    //trFoto.Start();
                    //Thread.Sleep(100);
                    TCallFoto();

                    /* -------------------------------
                     *  if NEXT, update called 
                     *  status
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        _dbKasir.UpdateFotoCalled(_tmpFoto.ID, _tmpFoto.Nomor);
                        _tmpFoto.ID = ConvertID(_tmpFoto.ID);
                    }

                    /* -------------------------------
                     *  show on BOX
                     * ------------------------------- */
                    lblFoto.Text = _tmpFoto.NomorAntrian;
                    lblFoto.Refresh();

                    break;

                case "WAWANCARA":

                    /* -------------------------------
                     *  if NEXT
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        int i = 0;
                        int n = 0;

                        /* -------------------------------
                         *  FLIP FLOP
                         * ------------------------------- */
                        while (i == 0 && n <= 1)
                        {
                            /* get next number
                             * by current id */
                            _tmpWawancara.Nomor = new KasirBase().GetWawancaraNextNumber(_tmpWawancara.ID);
                            i = _tmpWawancara.Nomor;
                            n++;

                            /* if not found, convert id into another
                             * and repeat the process */
                            if (i == 0) _tmpWawancara.ID = ConvertID(_tmpWawancara.ID);
                            _tmpWawancara.ReplayID = _tmpWawancara.ID;
                        }
                    }

                    /* -------------------------------
                     *  if NOT FOUND
                     * ------------------------------- */
                    if (_tmpWawancara.Nomor == 0)
                    {
                        var tbell = new Thread(TPlayBell);
                        tbell.Start();
                        Thread.Sleep(100);

                        break;
                    }

                    /* -------------------------------
                     *  set value for calling
                     * ------------------------------- */
                    _tmpWawancara.NomorAntrian =
                        string.Format("{0}-{1}", _tmpWawancara.ReplayID,
                                      _tmpWawancara.Nomor.ToString().Trim().PadLeft(3, '0'));

                    _tmpWawancara.LoketID = loketid;
                    _tmpWawancara.LoketDescription = loketDesc;

                    /* -------------------------------
                     *  calling
                     * ------------------------------- */
                    //var trWawancara = new Thread(TCallWawancara);
                    //trWawancara.Start();
                    //Thread.Sleep(100);
                    TCallWawancara();

                    /* -------------------------------
                     *  if NEXT, update called 
                     *  status
                     * ------------------------------- */
                    if (_keymap.Action == 0)
                    {
                        _dbKasir.UpdateWawancaraCalled(_tmpWawancara.ID, _tmpWawancara.Nomor);
                        _tmpWawancara.ID = ConvertID(_tmpWawancara.ID);
                    }

                    /* -------------------------------
                     *  show on BOX
                     * ------------------------------- */
                    lblWawancara.Text = _tmpWawancara.NomorAntrian;
                    lblWawancara.Refresh();

                    break;
            }

            // end process
            _stillProcessing = false;

        }

        /// <summary>
        /// Converts the ID.
        /// </summary>
        /// <param name="oldid">The oldid.</param>
        /// <returns></returns>
        private static string ConvertID(string oldid)
        {
            return oldid == "B" ? "C" : "B";
        }

        /// <summary>
        /// Handles the Shown event of the MainScreen control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MainScreen_Shown(object sender, EventArgs e)
        {
            /* -------------------------------
             *  load CLOCK
             * ------------------------------- */
            var t1 = new Thread(LoadClock);
            t1.Start();
        }

        #region Calling

        /// <summary>
        /// Ts the widget.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="desc">The desc.</param>
        /// <param name="num">The num.</param>
        private static void TWidget(string id, string desc, string num)
        {
            using (var qnum = new QWNumber())
            {
                qnum.Show();
                Application.DoEvents();
                qnum.Focus();
                Application.DoEvents();
                qnum.Play(id, desc, num);
            }
        }

        /// <summary>
        /// Ts the call berkas.
        /// </summary>
        private void TCallBerkas()
        {
            TWidget(_tmpBerkas.LoketID, _tmpBerkas.LoketDescription, _tmpBerkas.NomorAntrian);
        }

        /// <summary>
        /// Ts the call bayar.
        /// </summary>
        private void TCallBayar()
        {
            TWidget(_tmpBayar.LoketID, _tmpBayar.LoketDescription, _tmpBayar.NomorAntrian);
        }

        /// <summary>
        /// Ts the call foto.
        /// </summary>
        private void TCallFoto()
        {
            TWidget(_tmpFoto.LoketID, _tmpFoto.LoketDescription, _tmpFoto.NomorAntrian);
        }

        /// <summary>
        /// Ts the call wawancara.
        /// </summary>
        private void TCallWawancara()
        {
            TWidget(_tmpWawancara.LoketID, _tmpWawancara.LoketDescription, _tmpWawancara.NomorAntrian);
        }

        #endregion

        #region Background Image

        /// <summary>
        /// Sets the background image.
        /// </summary>
        private void SetBackgroundImage()
        {
            if (InvokeRequired)
            {
                var o = new DelegateThis(SetBackgroundImage);
                Invoke(o);
            }
            else
            {
                BackgroundImage = Resources.kde;
            }
        }

        /// <summary>
        /// Sets the panel1 image.
        /// </summary>
        private void SetPanel1Image()
        {
            if (pnl1.InvokeRequired)
            {
                var o = new DelegateThis(SetPanel1Image);
                pnl1.Invoke(o);
            }
            else
            {
                pnl1.BackgroundImage = Resources.widget_black320;
            }
        }

        /// <summary>
        /// Sets the panel2 image.
        /// </summary>
        private void SetPanel2Image()
        {
            if (pnl2.InvokeRequired)
            {
                var o = new DelegateThis(SetPanel2Image);
                pnl2.Invoke(o);
            }
            else
            {
                pnl2.BackgroundImage = Resources.widget_black320;
            }
        }

        /// <summary>
        /// Sets the panel3 image.
        /// </summary>
        private void SetPanel3Image()
        {
            if (pnl3.InvokeRequired)
            {
                var o = new DelegateThis(SetPanel3Image);
                pnl3.Invoke(o);
            }
            else
            {
                pnl3.BackgroundImage = Resources.widget_black320;
            }
        }

        /// <summary>
        /// Sets the panel4 image.
        /// </summary>
        private void SetPanel4Image()
        {
            if (pnl4.InvokeRequired)
            {
                var o = new DelegateThis(SetPanel4Image);
                pnl4.Invoke(o);
            }
            else
            {
                pnl4.BackgroundImage = Resources.widget_black320;
            }
        }

        /// <summary>
        /// Sets the panel press image.
        /// </summary>
        private void SetPanelPressImage()
        {
            if (pnl4.InvokeRequired)
            {
                var o = new DelegateThis(SetPanelPressImage);
                pnlPress.Invoke(o);
            }
            else
            {
                pnlPress.BackgroundImage = Resources.wbox2;
            }
        }

        /// <summary>
        /// Loads the clock.
        /// </summary>
        private void LoadClock()
        {
            if (InvokeRequired)
            {
                var o = new DelegateThis(LoadClock);
                Invoke(o);
            }
            else
            {
                _clockWidget = new QWClock {Location = new Point(0, 10)};
                pnlRight.Controls.Add(_clockWidget);
            }
        }

        /// <summary>
        /// Loads the press images.
        /// </summary>
        private void LoadPressImages()
        {
            if (InvokeRequired)
            {
                var o = new DelegateThis(LoadPressImages);
                Invoke(o);
            }
            else
            {
                _pressWidget = new QWPress {Dock = DockStyle.Fill};
                pnlImage.Controls.Add(_pressWidget);
            }
        }

        #endregion

        #region Nested type: DelegateThis

        /// <summary>
        /// DelegateThis
        /// </summary>
        private delegate void DelegateThis();

        #endregion
    }
}